package servlets;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Set;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import EJBPackage.Abilita;
import EJBPackage.Notifica;
import EJBPackage.Utente;
import ejbSessions.ManagerAbilitaRemote;
import ejbSessions.ManagerAiutoRemote;
import ejbSessions.ManagerUtenteRemote;

/**
 * Servlet implementation class InterazioneAdmin
 */
public class InterazioneAdmin extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public InterazioneAdmin() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		gestisciRichiesta(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		gestisciRichiesta(request, response);
	}

	private void gestisciRichiesta(HttpServletRequest request, HttpServletResponse response){
		int idUtente;
		boolean redirect = false;
		HttpSession session = request.getSession();
		RequestDispatcher dispatcher = request.getRequestDispatcher("/Utente/InterazioneAdmin.jsp");
		try{
			Hashtable<String,String> env = new Hashtable<String,String>();
			env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
			env.put(Context.PROVIDER_URL,"localhost:1099");
			InitialContext jndiContext = new InitialContext(env);
			Object ref = jndiContext.lookup("ManagerUtente/remote");
			ManagerUtenteRemote managerUtente = (ManagerUtenteRemote)ref;
			
			Object idUtenteObj = session.getAttribute("userid");
			if(idUtenteObj!=null){
				idUtente = (Integer) idUtenteObj;
				Utente utente = managerUtente.getUtente(idUtente);
				Set<Notifica> notifiche = utente.getNotifica();
				session.setAttribute("notifiche", notifiche);
			}else{
				redirect = true;
				response.sendRedirect("./");
			}		
		}catch(Exception e){
			e.printStackTrace();
		}
		
		try {
			if(!redirect){
				dispatcher.forward(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		

	
	}
}
